package com.tledu.data.imports.controller;


import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.tledu.data.imports.entity.TdRawWaterType;
import com.tledu.data.imports.service.IAllFroms;
import com.tledu.data.imports.listener.EasyExcelListener;
import com.tledu.data.imports.service.ITdRawWaterTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 原料水检测分类Controller
 *
 * @author ruoyi
 * @date 2024-12-16
 */
@RestController
@RequestMapping("/type")
public class TdRawWaterTypeController extends BaseController
{
    @Autowired
    private IAllFroms allFroms;

    @PostMapping(value = "/excel/upload")
    public AjaxResult upload( @RequestParam(value = "file") MultipartFile file, @RequestParam(value = "prjectId") Long prjectId, HttpServletResponse response) throws IOException {
        // step1. 读取excel内容
        EasyExcelListener easyExcelListener = new EasyExcelListener();
        ExcelReaderBuilder read = EasyExcelFactory.read(file.getInputStream(), easyExcelListener);
        ExcelReader excelReader = read.build();
        // step2. 获取各个sheet页信息
        List<ReadSheet> sheets = excelReader.excelExecutor().sheetList();
        // step3. 获取各个Shhet页表格内容存于map
        Map<Integer, List<LinkedHashMap>> sheetInfos = new HashMap<>(sheets.size());
        List<String> errList = new ArrayList<>();
        for (ReadSheet sheet : sheets) {
            Integer sheetNo = sheet.getSheetNo();
            excelReader.read(sheet);
            sheetInfos.put(sheetNo, easyExcelListener.getListMap());
        }
        try {
            allFroms.setProjectId(prjectId);
            errList=allFroms.saveExcelInfo(sheetInfos);
            if(errList.size()!=0){
                return new AjaxResult(203,"导入错误",errList);
            }
        }catch (Exception e){

        }
        finally {
            allFroms.clearList();
        }
        return AjaxResult.success("导入成功");
    }

}